<template>
  <el-drawer
    v-model="drawer"
    class="drawer-layout"
    size="400px"
    :title="title"
    direction="rtl"
    :before-close="handleClose"
    :close-on-click-modal="false"
  >
    <div class="info-container">
      <div class="info-container_body">
        <div class="form-section">
          <el-form ref="refFrom" label-position="top" :model="form.model">
            <AgelFormDesc :items="form.items" :column="1"> </AgelFormDesc>

            <!-- 
            <AgelFormGrid :items="form.items" :span="24" :gutter="16">
              <template #slot-station>
                <station-select v-model="form.model.stationId" @change="stationChange"></station-select>
              </template>
              <template #slot-current>
                <el-input type="number" v-model="form.model.meterReadingCurrent" @blur="curChange"></el-input>
              </template> 
            </AgelFormGrid>-->
          </el-form>
        </div>
      </div>
      <div class="info-container_footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script setup name="RecordAdd" lang="ts">
import { addEnergyRecord, editEnergyRecord, getEnergySummary } from '@/api/station/energy/index';
import { StationEnergyRecord, BizStationEnergySummaryVo } from '@/api/station/energy/types';
import common from '@/utils/common';
import StationSelect from '@/views/common/station-select/index.vue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const defaultModel = (): StationEnergyRecord => ({
  settleId: undefined,
  stationId: '',
  startFrom: '',
  endTo: '',
  settleTime: common.dateFormat(new Date()),
  meterReadingPrevious: 0,
  meterReadingCurrent: 0,
  amount: 0,
  settleStartFrom: '',
  settleEndTo: ''
});
const drawer = ref(false);
const title = ref('新增电量');
const isEdit = ref(false);
const lastMeterReading = ref(0);
const form = reactive<any>({
  model: defaultModel(),
  items: [
    // { prop: 'stationId', label: '关联站房', required: true, slot: 'slot-station' },
    {
      prop: 'startFrom',
      label: '开始时间',
      slot: 'el-date-picker',
      attrs: { type: 'date', valueFormat: 'YYYY-MM-DD HH:mm:ss', defaultTime: new Date(0, 0, 0, 0, 0, 0), placeholder: '请选择' }
    },
    {
      prop: 'endTo',
      label: '结束时间',
      required: true,
      slot: 'el-date-picker',
      attrs: { type: 'date', valueFormat: 'YYYY-MM-DD HH:mm:ss', defaultTime: new Date(), placeholder: '请选择' }
    },

    {
      prop: 'amount',
      label: '期初数',
      attrs: { type: 'number' },
      rules: [{ required: true, min: 0, message: '期初数不能小于0', trigger: 'blur' }]
    },
    {
      prop: 'meterReadingCurrent',
      label: () => '电表读数' + (lastMeterReading.value ? '(上次电表读数：' + lastMeterReading.value + ')' : ''),
      required: true,
      slot: 'slot-current',
      rules: [
        { required: true, message: '电表读数比必填', trigger: 'blur' }
        // { min: lastMeterReading.value, message: '电表读数不能小于上次电表读数', trigger: 'blur' }
      ]
    }, // 当前读书
    {
      prop: 'settleStartFrom',
      label: '归属结算周期起始',
      required: true,
      slot: 'el-date-picker',
      attrs: { required: true, type: 'date', valueFormat: 'YYYY-MM-DD HH:mm:ss', defaultTime: new Date(0, 0, 0, 0, 0, 0), placeholder: '请选择' }
    },
    {
      prop: 'settleEndTo',
      label: '归属结算周期结束',
      required: true,
      slot: 'el-date-picker',
      attrs: { required: true, type: 'date', valueFormat: 'YYYY-MM-DD HH:mm:ss', defaultTime: new Date(), placeholder: '请选择' }
    },
    {
      prop: 'settleTime',
      label: '当前登记时间',
      required: true,
      slot: 'el-date-picker',
      attrs: { required: true, type: 'date', valueFormat: 'YYYY-MM-DD HH:mm:ss', readonly: true, defaultTime: new Date(), placeholder: '请选择' }
    }
  ]
});
const loading = ref(false);
const refFrom = ref<ElFormInstance>();
const emits = defineEmits(['close', 'success']);

const open = (id: string | number | undefined) => {
  if (id) {
    form.model.stationId = id;
    stationChange(form.model as BizStationEnergySummaryVo);
  }
  title.value = '新增电量登记';
  isEdit.value = false;
  drawer.value = true;
  refFrom.value?.clearValidate();
};
const openEdit = (row: any) => {
  title.value = '电量详情';
  isEdit.value = true;
  form.model = row;
  drawer.value = true;
  refFrom.value?.clearValidate();
};
// 选择站房change
const stationChange = async (info: BizStationEnergySummaryVo) => {
  form.model.startFrom = info.lastSettleTime || '';
  try {
    let res = await getEnergySummary(info.stationId);
    form.model.startFrom = res.data.lastSettleTime || '';
    lastMeterReading.value = +res.data.lastMeterReading || 0;
    form.model.meterReadingPrevious = +res.data.lastMeterReading || 0;
    // form.model.amount = +res.data.lastMeterReading || 0;
  } catch (err) {
    console.log(err);
  }
};
const curChange = () => {
  form.model.amount = +(form.model.meterReadingCurrent || 0) - +(form.model.meterReadingPrevious || 0);
  // form.model.amount = form.model.lastMeterReading;
};
/** 取消 */
const handleClose = () => {
  form.model = defaultModel();
  refFrom.value?.clearValidate();
  drawer.value = false;
  emits('close');
};
/** 确认 */
const handleSubmit = async () => {
  if (!refFrom.value) return;
  refFrom.value.validate((valid, fields) => {
    if (valid) {
      handleRequest();
    } else {
      console.log('error submit!', fields);
    }
  });
};
const handleRequest = async () => {
  loading.value = true;
  let serviceMethod = isEdit.value ? editEnergyRecord : addEnergyRecord;
  let res = await serviceMethod(form.model as StationEnergyRecord);
  loading.value = false;
  if (res.code == 200) {
    proxy?.$modal.msgSuccess('操作成功！');
    emits('success');
  } else {
    proxy?.$modal.msgError(res.msg || '操作失败！');
  }
};
defineExpose({ open, openEdit });
</script>
